import os
import subprocess
import time
import signal
import sys

# 日志目录
log_dir = os.path.join('.', 'simple_cpu_results', 'tensorboard_logs')

# 检查日志目录是否存在
if not os.path.exists(log_dir):
    print(f"错误: 日志目录不存在: {log_dir}")
    print("请先运行 simple_cpu_finetune.py 生成训练日志")
    sys.exit(1)

# 构建命令
command = [
    'tensorboard',
    '--logdir', log_dir,
    '--host', 'localhost',
    '--port', '6006'
]

print(f"正在启动TensorBoard服务...")
print(f"日志目录: {log_dir}")
print(f"访问地址: http://localhost:6006/")
print("按 Ctrl+C 停止服务")

# 启动进程
process = subprocess.Popen(
    command,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    universal_newlines=True
)

# 处理终止信号
def signal_handler(sig, frame):
    print("正在停止TensorBoard服务...")
    process.terminate()
    try:
        process.wait(timeout=5)
    except subprocess.TimeoutExpired:
        process.kill()
    print("TensorBoard服务已停止")
    sys.exit(0)

# 注册信号处理器
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

# 打印输出
try:
    for line in process.stdout:
        print(line.strip())
except KeyboardInterrupt:
    signal_handler(signal.SIGINT, None)

# 等待进程结束
process.wait()